<template>
  <div class="market_cardactivity_card_edit Row_content" style="width: 890px">
    <Form inline ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="120">
      <FormItem label="门店名称：" prop="shopId">
        <vueTreeselectChoice
          ref="vueTreeselectChoice"
          permissionCode="moms:market:cardactivityview"
          v-model="formValidate.shopId"
          :width="280"
          :disable-branch-nodes="true"
        ></vueTreeselectChoice>
      </FormItem>
      <FormItem label="活动名称：" prop="activityName">
        <Input placeholder="请输入" class="input-wid" @on-keyup="filterActivityName" @on-blur="filterActivityName" :maxlength="15" v-model="formValidate.activityName"></Input>
      </FormItem>
      <FormItem label="活动成本率：" prop="costRate">
        <Input placeholder="请输入活动成本率10%~20%" class="input-wid" v-model="formValidate.costRate" @on-keyup="filterCostRate(false)" @on-blur="filterCostRate(true)">
          <span slot="append">%</span>
        </Input>
      </FormItem>
      <FormItem label="门店币值：" prop="shopCoinQty">
        <Input placeholder="自动计算上个月门店平均币值" class="input-wid" disabled v-model="formValidate.shopCoinQty"></Input>
      </FormItem>
      <div class="award-form"
        v-for="(award, index) in awards"
        :key="index">
        <Form :ref="`award${index}`"
          inline
          :model="award"
          :rules="awardsValidate[index]"
          :label-width="120">
          <FormItem label="奖品名称：" prop="awardName">
            <Input search placeholder="请选择实物奖品" class="input-wid" v-model="award.awardName" @on-focus="selectAward($event, index)"></Input>
          </FormItem>
          <FormItem label="奖品单价：" prop="awardPrice">
            <Input placeholder="自动计算" class="input-wid" v-model="award.awardPrice" disabled></Input>
          </FormItem>
          <FormItem label="奖品数量上限：" prop="awardTotalQty">
            <Input placeholder="请输入1～100" class="input-wid" v-model="award.awardTotalQty" @on-keyup="filterNumber(award)" @on-blur="filterBlur(award)" :maxlength="3"></Input>
          </FormItem>
          <FormItem label="碎片数量：" prop="fragmentQty">
            <Select v-model="award.fragmentQty">
              <Option v-for="item in [{label: '4', value: 4}, {label: '6', value: 6}, {label: '9', value: 9}]" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
          <FormItem label="核心碎片数量：" prop="awardTotalQty">
            <Input placeholder="自动计算" class="input-wid" v-model="award.awardTotalQty" disabled></Input>
          </FormItem>
          <FormItem label="单组奖品成本：" prop="costPrice">
            <Input placeholder="自动计算" class="input-wid" v-model="award.costPrice" disabled></Input>
          </FormItem>
          <FormItem>
            <Button type="primary"
              @click="lookFragment(award, index)"
                >查看碎片</Button>
          </FormItem>
        </Form>
        <div class="operater">
          <i class="iconsys icondel"
            title="删除"
            @click="deleteAward(index)"></i>
        </div>
      </div>
      <FormItem>
        <Button type="primary"
          class="system-submit-btn"
          @click="addAward"
          >新增奖品组<Icon type="ios-add" /></Button>
        <span>最多可设置三组</span>
      </FormItem>
      <FormItem></FormItem>
      <FormItem label="活动总成本：" prop="costQty">
        <Input placeholder="自动计算" class="input-wid" disabled v-model="formValidate.costQty"></Input>
      </FormItem>
      <FormItem label="吸币量：" prop="suctionCoinQty">
        <Input placeholder="自动计算" class="input-wid" disabled v-model="formValidate.suctionCoinQty"></Input>
      </FormItem>
      <FormItem label="卡片总张数：" prop="totalCardNum">
        <Input placeholder="自动计算" class="input-wid" disabled v-model="formValidate.totalCardNum"></Input>
      </FormItem>
      <FormItem label="赠币总数量：" prop="totalCoins">
        <Input placeholder="自动计算" class="input-wid" disabled v-model="formValidate.totalCoins"></Input>
      </FormItem>
      <FormItem label="卡片盒数/盒：" prop="boxQty">
        <Input placeholder="自动计算" class="input-wid" disabled v-model="formValidate.boxQty"></Input>
      </FormItem>
      <FormItem></FormItem>
      <FormItem label="配置赠币数量：" style="width: 830px" prop="couponList">
        <Table stripe :columns="columns" :data="formValidate.couponList" style="width: 600px">
          <template slot-scope="{ row }" slot="input">
            <Input placeholder="自动计算" disabled v-model="row.couponQty"></Input>
          </template>
        </Table>
      </FormItem>
      <FormItem class="form-btn"
              style="margin-top: 5px;">
        <Button type="primary"
                class="system-submit-btn"
                @click="handleSubmit"
                >确定</Button>
        <Button class="system-submit-btn"
                @click="handleReset"
                style="margin-left: 8px">取消</Button>
      </FormItem>
    </Form>
    <select-award :show="drawAwardShow" :shop-id="formValidate.shopId" :select-index="selectAwardIndex" :all-form="awards" @close="drawAwardShow = false" @ensure="selectedAward"></select-award>
    <fragment-card :show="drawShow" :fragments="fragments" :mode="mode" @on-close="drawShow = false" :important="importantFragment"></fragment-card>
  </div>
</template>

<script>
import { routeEqual } from '@/libs/util'
import { mapState } from 'vuex'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import SelectAward from '@/view/components/select-award/index.vue'
import { couponCalculate, searchCoin, calculateMoney, cardUpdate, fragmentCard, cardDetail } from '@/api/market/cardactivity/card.js'
import FragmentCard from './fragmentCard.vue'
export default {
  name: 'market_cardactivity_card_edit',
  components: { vueTreeselectChoice, SelectAward, FragmentCard },
  data () {
    return {
      id: '',
      formValidate: {
        shopId: null,
        activityName: '',
        costRate: '',
        shopCoinQty: '',
        costQty: '',
        suctionCoinQty: '',
        totalCoins: '',
        totalCardNum: '',
        boxQty: '',
        couponList: [
          { couponName: '3枚游戏币', couponDenomination: '3', couponQty: '', couponType: -1 },
          { couponName: '5枚游戏币', couponDenomination: '5', couponQty: '', couponType: -1 },
          { couponName: '10枚游戏币', couponDenomination: '10', couponQty: '', couponType: -1 }
        ]
      },
      awards: [],
      awardsValidate: [],
      ruleValidate: {
        shopId: { required: true, message: '请选择门店', trigger: 'change' },
        activityName: { required: true, message: '请输入活动名称', trigger: 'blur' },
        costRate: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!this.formValidate.costRate) {
              callback(new Error('请输入活动成本率'))
            } else if (this.formValidate.costRate < 10 || this.formValidate.costRate > 20) {
              callback(new Error('活动成本率10%~20%'))
            } else {
              callback()
            }
          }
        },
        shopCoinQty: { required: true, message: '自动计算门店币值失败' },
        costQty: {
          required: true,
          validator: (rule, value, callback) => {
            if (!this.formValidate.costQty) {
              callback(new Error('自动计算活动总成本失败'))
            } else if (+this.formValidate.costQty < 1500) {
              callback(new Error('活动总成本必须大于等于1500'))
            } else {
              callback()
            }
          }
        },
        suctionCoinQty: { required: true, message: '自动计算吸币量失败' },
        totalCoins: { required: true, message: '自动计算赠币总数量失败' },
        totalCardNum: { required: true, message: '自动计算卡片总张数失败' },
        boxQty: { required: true, message: '自动计算卡片盒数/盒失败' },
        couponList: {
          required: true,
          validator: (rule, value, callback) => {
            let flag = false
            this.formValidate.couponList.forEach(item => {
              if (item.couponQty === '') {
                flag = true
              }
            })
            if (flag) {
              callback(new Error('请配置赠币数量'))
            } else {
              callback()
            }
          }
        }
      },
      columns: [
        {
          title: '赠币名称',
          key: 'couponName'
        },
        {
          title: '面额',
          key: 'couponDenomination'
        },
        {
          title: '数量',
          slot: 'input'
        }
      ],
      drawAwardShow: false,
      // 碎片
      selectAwardIndex: -1,
      drawShow: false,
      fragments: [],
      importantFragment: '',
      mode: 4,
      getDetailDone: false
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    })
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.id !== to.query.id) {
        vm.getDetailDone = false
        vm.id = to.query.id
        vm.shopId = to.query.shopId
        vm.getDetail()
      } else {
        vm.calcCoupon(false)
      }
    })
  },
  watch: {
    'formValidate.shopId' (val) {
      if (this.getDetailDone) {
        this.$refs.formValidate.validateField('shopId')
        this.awards = []
        this.awardsValidate = []
        this.selectAwardIndex = -1
        if (val) {
          this.getAverageCoin()
        }
      }
      this.getDetailDone = true
    }
  },
  mounted () {
    const query = this.$route.query
    this.id = query.id
    this.shopId = query.shopId
    this.getDetail()
  },
  methods: {
    getDetail () {
      cardDetail({
        merchantId: this.merchantId,
        shopId: this.shopId,
        activityCardId: this.id
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          const form = result.data || {}
          this.awards = form.awardList
          this.awards.forEach(() => {
            this.awardsValidate.push({
              awardName: { required: true, message: '请选择实物奖品', trigger: 'change' },
              awardPrice: { required: true, message: '自动计算奖品单价失败' },
              awardTotalQty: { required: true, message: '请输入奖品数量上限' },
              fragmentQty: { required: true, message: '请选择碎片数量' },
              costPrice: { required: true, message: '自动计算单组奖品成本失败' }
            })
          })
          this.formValidate = {
            shopId: form.shopId,
            activityName: form.activityName,
            costRate: form.costRate,
            shopCoinQty: form.shopCoinQty,
            costQty: form.costQty,
            suctionCoinQty: form.suctionCoinQty,
            totalCoins: form.coinQty,
            totalCardNum: form.cardQty,
            boxQty: form.boxQty,
            couponList: form.couponList.sort((item1, item2) => item1.couponDenomination - item2.couponDenomination)
          }
          this.calcCoupon()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    handleSubmit () {
      if (!this.awards.length) {
        this.$Message.error('请添加奖品组')
        return
      }
      let flag = true
      this.awards.forEach((item, index) => {
        this.$refs['award' + index][0].validate(val => {
          if (!val) {
            flag = false
          }
        })
      })
      this.$refs.formValidate.validate(val => {
        if (val && flag) {
          const formValidate = this.formValidate
          cardUpdate({
            merchantId: this.merchantId,
            shopId: formValidate.shopId,
            activityCardId: this.id,
            activityName: formValidate.activityName,
            costRate: formValidate.costRate,
            shopCoinQty: formValidate.shopCoinQty,
            couponList: formValidate.couponList,
            awardList: this.awards,
            operatorId: this.userId,
            operatorName: this.userName
          }).then(res => {
            const result = res.data || {}
            if (result.status === 200) {
              this.$Message.success('编辑成功！')
              this.handleReset()
            } else {
              this.$Message.error(`${result.error}`)
            }
          }).catch(err => {
            this.$Message.error(`${err}`)
          })
        }
      })
    },
    calculateMoney () {
      const formValidate = this.formValidate
      let flag = true
      const awardPrices = this.awards.map(item => {
        if (!item.costPrice) {
          flag = false
        }
        return item.costPrice
      })
      if (formValidate.costRate && formValidate.shopCoinQty && flag && this.awards.length) {
        calculateMoney({
          merchantId: this.merchantId,
          costRate: formValidate.costRate,
          shopCoinQty: formValidate.shopCoinQty,
          awardPrices
        }).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            this.formValidate.costQty = result.data.costQty
            this.formValidate.suctionCoinQty = result.data.suctionCoinQty
            this.formValidate.totalCardNum = result.data.cardQty
            this.formValidate.totalCoins = result.data.coinQty
            this.formValidate.boxQty = result.data.boxQty
            this.calcCoupon()
          } else {
            this.$Message.error(`${result.error}`)
          }
        }).catch(err => {
          this.$Message.error(`${err}`)
        })
      }
      if (!this.awards.length) {
        this.formValidate.costQty = ''
        this.formValidate.suctionCoinQty = ''
        this.formValidate.totalCardNum = ''
        this.formValidate.totalCoins = ''
        this.formValidate.boxQty = ''
        this.formValidate.couponList.forEach(item => {
          item.couponQty = ''
        })
      }
    },
    selectAward ($event, index) {
      $event.target.blur()
      if (this.formValidate.shopId) {
        this.selectAwardIndex = index
        this.drawAwardShow = true
      } else {
        this.$refs.formValidate.validateField('shopId')
      }
    },
    addAward () {
      if (this.awards.length < 3) {
        this.awards.push({
          awardName: '',
          awardPic: '',
          skuId: '',
          categoryId: '',
          awardPrice: '',
          awardTotalQty: '',
          fragmentQty: '',
          costPrice: ''
        })
        this.awardsValidate.push({
          awardName: { required: true, message: '请选择实物奖品', trigger: 'change' },
          awardPrice: { required: true, message: '自动填充奖品单价失败' },
          awardTotalQty: { required: true, message: '请输入奖品数量上限' },
          fragmentQty: { required: true, message: '请选择碎片数量' },
          costPrice: { required: true, message: '自动计算单组奖品成本失败' }
        })
      }
    },
    selectedAward (award) {
      this.awards[this.selectAwardIndex].awardName = award.productName
      this.awards[this.selectAwardIndex].awardPic = award.productImgs[0]
      this.awards[this.selectAwardIndex].skuId = award.productSku
      this.awards[this.selectAwardIndex].categoryId = award.categoryCode
      this.awards[this.selectAwardIndex].awardPrice = award.price
      this.calcOneMoney(this.awards[this.selectAwardIndex])
      this.calculateMoney()
      this.drawAwardShow = false
    },
    deleteAward (index) {
      this.$refs['award' + index][0].resetFields()
      this.awards[index] = {
        awardName: '',
        awardPic: '',
        skuId: '',
        categoryId: '',
        awardPrice: '',
        awardTotalQty: '',
        fragmentQty: '',
        costPrice: ''
      }
      this.selectAwardIndex = -1
      this.awards.splice(index, 1)
      this.calculateMoney()
    },
    calcCoupon (needValiDate = true) {
      const formValidate = this.formValidate
      if (formValidate.boxQty && formValidate.totalCardNum) {
        couponCalculate({
          merchantId: this.merchantId,
          coupons: formValidate.couponList.map(item => +item.couponDenomination),
          totalCoins: formValidate.totalCoins,
          boxQty: formValidate.boxQty
        }).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            this.formValidate.couponList.forEach(item => {
              item.couponQty = result.data[item.couponDenomination]
            })
          } else {
            this.clearCoupon()
            this.$Message.error(`${result.error}`)
          }
        }).catch(err => {
          this.clearCoupon()
          this.$Message.error(`${err}`)
        })
      } else if (needValiDate) {
        this.$refs.formValidate.validate()
      }
    },
    clearCoupon () {
      this.formValidate.couponList.forEach(item => {
        item.couponQty = ''
      })
    },
    getAverageCoin () {
      searchCoin({
        merchantId: this.merchantId,
        shopId: this.formValidate.shopId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.formValidate.shopCoinQty = result.data
          this.calculateMoney()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    calcOneMoney (award) {
      if (award.awardPrice && award.awardTotalQty) {
        award.costPrice = +((award.awardPrice * award.awardTotalQty).toFixed(2))
      }
    },
    filterNumber (award) {
      award.awardTotalQty = (award.awardTotalQty + '').replace(/[^\d]/g, '').replace(/^0{1,}/g, '')
      let value = award.awardTotalQty
      if (value > 100) {
        award.awardTotalQty = value.substr(0, value.length - 1)
      }
      return award
    },
    filterBlur (award) {
      const item = this.filterNumber(award)
      this.calcOneMoney(item)
      this.calculateMoney()
    },
    lookFragment (award, index) {
      this.fragments = []
      if (award.skuId && award.fragmentQty) {
        fragmentCard({
          merchantId: this.merchantId,
          activityAwardId: award.skuId,
          type: 0,
          awardPic: award.awardPic,
          fragmentQty: award.fragmentQty
        }).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            this.drawShow = true
            this.mode = award.fragmentQty
            this.fragments = result.data || []
            const importantFragments = this.fragments.filter(item => item.fragmentType === 1)
            this.importantFragment = importantFragments[0] ? importantFragments[0].fragmentNo : ''
          } else {
            this.$Message.error(`${result.error}`)
          }
        }).catch(err => {
          this.$Message.error(`${err}`)
        })
      } else {
        this.$refs['award' + index][0].validateField('awardName')
        this.$refs['award' + index][0].validateField('fragmentQty')
      }
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'market_cardactivity_card'
        })
      })
    },
    filterActivityName () {
      this.formValidate.activityName = this.formValidate.activityName.replace(/[^a-zA-Z0-9\u4E00-\u9FA5]/g, '')
    },
    filterCostRate (needCalc) {
      this.formValidate.costRate = (this.formValidate.costRate + '').replace(/[^0-9]/g, '')
      if (this.formValidate.costRate.length > 1 && this.formValidate.costRate[0] === '0') {
        this.formValidate.costRate = this.formValidate.costRate.substr(1, 1)
      }
      if (needCalc) {
        this.calculateMoney()
      }
    }
  }
}
</script>

<style lang='less'>
  .market_cardactivity_card_edit {
    .input-wid {
      width: 280px;
    }
  }
  .award-form {
    padding-top: 20px;
    margin-bottom: 20px;
    background: #F8F8F9;
    border: 1px solid #E9E9E9;
    border-radius: 3px;
    position: relative;
    &:last-child {
      margin-bottom: 0
    }
  }
  .operater {
    position: absolute;
    top: 50%;
    right: -15px;
    transform: translate(100%, -50%)
  }
</style>
